package com.gxs.ea.fileupload.beans.jsf.outbox;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;
import org.primefaces.model.LazyDataModel;
import org.primefaces.model.SelectableDataModel;
import org.primefaces.model.SortOrder;

import com.gxs.ea.fileupload.beans.data.model.CollectionSearchResults;
import com.gxs.ea.fileupload.beans.data.service.FileMetaCollectionService;

public class LazyFileTable extends LazyDataModel<Map<String, Object>> implements SelectableDataModel<Map<String, Object>>
{
	private static final long serialVersionUID = -7856911058573685193L;

	private List<Map<String, Object>> datasource;
	
	private Map<String, String> mapOfSearchFields;
	
	private FileMetaCollectionService fileMetaCollectionService;
	
	private String companyCode;
	
	public LazyFileTable(FileMetaCollectionService svc, String companyCode, Map<String, String> labelsForSearchableFields)
	{
		this.fileMetaCollectionService = svc;
		this.companyCode = companyCode;
		mapOfSearchFields = new HashMap<String, String>();
		
		for(String fieldName : labelsForSearchableFields.keySet())
		{
			mapOfSearchFields.put(fieldName, new String());
		}
	}
	
	@Override
	public Map<String, Object> getRowData(String rowKey)
	{
		for(Map<String, Object> o : datasource)
		{
			String currentKey = (String) o.get("_key");
			if(currentKey.equals(rowKey))
				return o;
		}
		return null;
	}
	
	@Override
	public Object getRowKey(Map<String, Object> o)
	{
		return o.get("_id");
	}
	
	@Override
	public List<Map<String, Object>> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, String> filters)
	{
		
		CollectionSearchResults results = this.fileMetaCollectionService.searchAll(companyCode, first, pageSize, sortField, (SortOrder.ASCENDING == sortOrder ? 1 : -1), filters, mapOfSearchFields);
		Long count = results.getTotalCount();
		List<Map<String, Object>> list = results.getListOfDBObjects();
		this.setRowCount(count.intValue());
		return list;
	}

	public FileMetaCollectionService getFileMetaCollectionService() {
		return fileMetaCollectionService;
	}

	public void setFileMetaCollectionService(
			FileMetaCollectionService fileMetaCollectionService) {
		this.fileMetaCollectionService = fileMetaCollectionService;
	}

	public List<Map<String, Object>> getDatasource() {
		return datasource;
	}

	public void setDatasource(List<Map<String, Object>> datasource) {
		this.datasource = datasource;
	}

	public Map<String, String> getMapOfSearchFields() {
		return mapOfSearchFields;
	}

	public void setMapOfSearchFields(Map<String, String> mapOfSearchFields) {
		this.mapOfSearchFields = mapOfSearchFields;
	}

	public String getCompanyCode() {
		return companyCode;
	}

	public void setCompanyCode(String companyCode) {
		this.companyCode = companyCode;
	}

	
}
